package  com.baomidou.springwind.controller;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.support.json.JSONUtils;
import com.baomidou.framework.common.util.DateUtil;
import com.baomidou.framework.controller.SuperController;
import com.baomidou.framework.upload.UploadFile;
import com.baomidou.framework.upload.UploadMsg;
import com.baomidou.framework.upload.UploadMultipartRequest;
import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.SSOToken;
import com.baomidou.kisso.annotation.Action;
import com.baomidou.kisso.annotation.Login;
import com.baomidou.kisso.annotation.Permission;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.springwind.common.HoorayosHelper;
import com.baomidou.springwind.entity.App;
import com.baomidou.springwind.entity.AppCategory;
import com.baomidou.springwind.entity.Member;
import com.baomidou.springwind.entity.MemberApp;
import com.baomidou.springwind.entity.MyPermission;
import com.baomidou.springwind.service.IAppCategoryService;
import com.baomidou.springwind.service.IAppService;
import com.baomidou.springwind.service.IMemberService;
import com.baomidou.springwind.service.IPermission1Service;
import com.baomidou.springwind.service.IPermissionService;

/**
 *  应用管理控制器首页
 * @author koumiba
 * @Date 2016-04-13
 */
@Controller
@RequestMapping("/sysapp/appmanage")
public class AppmanageController extends SuperController {
	@Autowired
	private IMemberService memberService;
	@Autowired
	private IPermission1Service permissonService;
	@Autowired
	private IAppService appService;
	@Autowired
	private IAppCategoryService appCategoryService;
	/**
	 * 主页
	 */
	@Login(action = Action.Skip)
	@Permission(action = Action.Skip)
	@RequestMapping("/index")
	public String index(Model model) {
		model.addAttribute("errorCode", HoorayosHelper.getErrorCodeMap());
		//验证是否登入
		if(!HoorayosHelper.checkLogin(request)){
			model.addAttribute("code", HoorayosHelper.getErrorCode("noLogin"));
			return "error";
		}
		//验证是否管理员
		int mid = HoorayosHelper.getMemberId(request);
		Member user = memberService.selectById(mid);
		if(!HoorayosHelper.checkAdmin(user)){
			model.addAttribute("code", HoorayosHelper.getErrorCode("noAdmin"));
			return "error";
		}
		// 验证权限
		int userPermissionId = user.getPermissionId().intValue(); 
		String appsId = permissonService.selectById(userPermissionId).getAppsId();
		if(!HoorayosHelper.checheckPermissions(appsId, "5")){
			model.addAttribute("code", HoorayosHelper.getErrorCode("noPermissions"));
			return "error";
		}
		List<AppCategory> appCategoryList = new AppCategory().selectAll();
		String appCategoryInfo = "";
		for(AppCategory ac : appCategoryList){
			appCategoryInfo += "<option value='"+ac.getTbid()+"'>"+ac.getName()+"</option>";
		}
			
		model.addAttribute("appCategoryInfo", appCategoryInfo);
			
		return "/sysapp/appmanage/index";
	}
	/**
	 * 详情
	 */
	@Login(action = Action.Skip)
	@Permission(action = Action.Skip)
	@RequestMapping("/detail")
	public String detail(Model model) {
		model.addAttribute("errorCode", HoorayosHelper.getErrorCodeMap());
		//验证是否登入
		if(!HoorayosHelper.checkLogin(request)){
			model.addAttribute("code", HoorayosHelper.getErrorCode("noLogin"));
			return "error";
		}
		//验证是否管理员
		int mid = HoorayosHelper.getMemberId(request);
		Member user = memberService.selectById(mid);
		if(!HoorayosHelper.checkAdmin(user)){
			model.addAttribute("code", HoorayosHelper.getErrorCode("noAdmin"));
			return "error";
		}
		// 验证权限
		int userPermissionId = user.getPermissionId().intValue(); 
		String appsId = permissonService.selectById(userPermissionId).getAppsId();
		if(!HoorayosHelper.checheckPermissions(appsId, "5")){
			model.addAttribute("code", HoorayosHelper.getErrorCode("noPermissions"));
			return "error";
		}
		
		String appId = request.getParameter("appid");	
		App app = new App();
		if(appId != null && !appId.equals("")){
			app = appService.selectById(Integer.parseInt(appId));
		}else{			
			app.setType("window");
			app.setIsresize(1);
			app.setIsopenmax(0);
			app.setIsflash(0);
			app.setVerifytype(0);
		}
		model.addAttribute("app",app);
		model.addAttribute("appid",appId);
		
		// 获取应用分类
		List<AppCategory> appCategoryList = new AppCategory().selectAll();
		String appCategoryInfo = "";
		for(AppCategory appc : appCategoryList){
			if(appc.getTbid() == app.getTbid() ){
				appCategoryInfo += "<option value='"+appc.getTbid()+"' selected>"+appc.getName()+"</option>";
			}else{
				appCategoryInfo += "<option value='"+appc.getTbid()+"'>"+appc.getName()+"</option>";
			}
		}
		model.addAttribute("appCategoryInfo",appCategoryInfo);
		return "/sysapp/appmanage/detail";
	}
	
	/**
	 * ajax页面
	 */
	@ResponseBody
	@Login(action = Action.Skip)
	@Permission(action = Action.Skip)
	@RequestMapping("/ajax")
	public String ajax(String ac) {
		String display = "";
		if (ac.equals("getList")){
			String search_1 = request.getParameter("search_1");
			String search_2 = request.getParameter("search_2");
			String search_3 = request.getParameter("search_3");
			String search_4 = request.getParameter("search_4");
			int from = Integer.parseInt(request.getParameter("from"));
			int to = Integer.parseInt(request.getParameter("to"));
			
			List<AppCategory> appCategoryList = new AppCategory().selectAll();
			Map<Integer, String> category = new HashMap<Integer, String>();
			for(AppCategory appc : appCategoryList){
				category.put(appc.getTbid().intValue(), appc.getName());
			}
			EntityWrapper ew = new EntityWrapper<App>();
			if(search_1 != null && !search_1.equals("")){
				ew.like("name", search_1);
			}
			if(search_2 != null && !search_2.equals("")){
				ew.and("app_category_id="+search_2);
			}
			if(search_3 != null && !search_3.equals("")){
				ew.and("type='"+search_3+"'");
			}
		
			int type = (search_4.equals("1") ? 1 :2);
			ew.and("verifytype="+type);

			List<App> rs = new App().selectList(ew);
			display += rs.size()+"<{|*|}>";
			
			for(int i=from; i<to && i<rs.size(); i++){
				App v = rs.get(i);
				
				display+="<tr class='list-bd'>";
				display+="<td>"+v.getTbid()+"</td>";
				display+="<td style='text-align:left;padding-left:15px'><img src='"+v.getIcon()+"' alt='"+v.getName()+"' class='appicon'><span class='appname'>"+v.getName()+"</span></td>";
				display+="<td>"+(v.getType().equals("window") ? "窗口" : "件")+"</td>";
				display+="<td>"+(v.getAppCategoryId() == 0 ? "未分类" : category.get(v.getAppCategoryId().intValue()))+"</td>";
				display+="<td>"+v.getUsecount()+"</td>";
				display+="<td>";
					if(v.getVerifytype() == 1){
						if(v.getIsrecommend() == 1){
							display+="<a href='javascript:;' class='btn btn-link'>今日推荐</a>";
						}else{
							display+="<a href='javascript:;' class='btn btn-link do-recommend' appid="+v.getTbid()+">设为今日推荐</a>";
						}
						display+="<a href='javascript:openDetailIframe(\"detail.html?appid="+v.getTbid()+"\");' class='btn btn-link'>编辑</a>";
					}else{
						display+="<a href='javascript:openDetailIframe(\"detail.html?appid="+v.getTbid()+"\");' class='btn btn-link'>查看详情</a>";
					}
					display+="<a href='javascript:;' class='btn btn-link do-del' appid="+v.getTbid()+">删除</a>";
				display+="</td>";
			display+="</tr>";
			}
			
		}else if (ac.equals("del")){
			int tbid = Integer.parseInt(request.getParameter("appid"));
			appService.deleteById(tbid);
		}else if (ac.equals("recommend")){
			EntityWrapper ew = new EntityWrapper<App>();
			ew.where("isrecommend=1");

			List<App> appList = new App().selectList(ew);
			for(App a : appList){
				a.setIsrecommend(0);
			}
			appService.insertOrUpdateBatch(appList);
			
			int appid = Integer.parseInt(request.getParameter("appid"));
			App app = appService.selectById(appid);
			app.setIsrecommend(1);
			appService.insertOrUpdate(app);
		}
		return display;
	
	}
	
	/**
	 * ajax页面
	 */
	@ResponseBody
	@Login(action = Action.Skip)
	@Permission(action = Action.Skip)
	@RequestMapping("/detailAjax")
	public String detailAjax(String ac) {
		if (ac.equals("edit")){
			int val_issetbar = request.getParameter("val_app_category_id") == "1" ? 0 : 1;
			String id = request.getParameter("id");
			App data = new App();
			if(id!=null && !id.equals("")){
				data = appService.selectById(Integer.parseInt(id));
			}
			data.setIcon(request.getParameter("val_icon"));
			data.setName(request.getParameter("val_name"));
			data.setAppCategoryId(Long.parseLong(request.getParameter("val_app_category_id")));
			data.setUrl(request.getParameter("val_url"));
			data.setWidth(Integer.parseInt(request.getParameter("val_width")));
			data.setHeight(Integer.parseInt(request.getParameter("val_height")));
			data.setIsresize(Integer.parseInt(request.getParameter("val_isresize")));
			data.setIsopenmax(Integer.parseInt(request.getParameter("val_isopenmax")));
			data.setIssetbar(request.getParameter("val_issetbar")!=null ? Integer.parseInt(request.getParameter("val_issetbar")) : 0);
			data.setIsflash(request.getParameter("val_isflash")!=null ? Integer.parseInt(request.getParameter("val_isflash")) : 0);
			data.setRemark(request.getParameter("val_remark"));
			
			if(id==null || id.equals("")){
				EntityWrapper ew = new EntityWrapper<App>();
				ew.orderBy("tbid", false);
				App app = new App().selectOne(ew);
				int nextAppId = app.getTbid().intValue()+1;
				data.setType(request.getParameter("val_remark"));
				data.setDt(new Date());
				data.setVerifytype(1);
				data.setTbid((long)nextAppId);
				appService.insert(data);
			}else{
				appService.insertOrUpdate(data);
			}		
			Map<String,String> result = new HashMap<String,String>();
			result.put("info", "");
			result.put("status", "y");
			return JSONUtils.toJSONString(result);
		}else if(ac.equals("pass")){
			String appId = request.getParameter("appid");
			App app = appService.selectById(Integer.parseInt(appId));
			app.setVerifytype(1);
			appService.insertOrUpdate(app);
		}else if(ac.equals("unpass")){
			String appId = request.getParameter("appid");
			String info = request.getParameter("info");
			App app = appService.selectById(Integer.parseInt(appId));
			app.setVerifytype(3);
			app.setVerifyinfo(info);
			appService.insertOrUpdate(app);
		}else if(ac.equals("uploadImg")){
			
			UploadMsg msg = new UploadMsg();
			try {
				UploadMultipartRequest umr = new UploadMultipartRequest(request, getSaveDir(), 2048000);
				umr.upload();
				Enumeration<?> files = umr.getFileNames();
				while ( files.hasMoreElements() ) {
					String name = (String) files.nextElement();
					UploadFile cf = umr.getUploadFile(name);
					if ( cf != null ) {
						Map<String, String> info = new HashMap<String, String>();
						info.put("url", getSurlPath()+cf.getFilename());
						info.put("fileType", cf.getType());
						info.put("original", cf.getOriginalFileName());
						info.put("state", cf.getUploadCode().key()+"");
						return JSONUtils.toJSONString(info);
					}
				}
			}catch ( IOException e ) {
				logger.error("uploadFile error. ", e);
			}	
		}
		return "";
	}
	
	
	/*************************
	 *    私有方法 
	 *************************/
	
	
	/**
	 * 验证是否为管理员
	 * @return Boolean
	 * koumiba
	 * 2017年3月26日
	 */
	private Boolean checkAdmin(){
		int mid = HoorayosHelper.getMemberId(request);
		EntityWrapper ew = new EntityWrapper(new Member());
		Member m = new Member().selectById(mid);
		return m.getType() == 1 ? true : false;
	}
	/**
	 * <p>
	 * 上传文件存放目录 uploads/shortcut/{yyyy}{mm}{dd}/{time}{rand:6}
	 * </p>
	 */
	private String getSaveDir() {
		StringBuffer filePath = new StringBuffer(session.getServletContext().getRealPath("/"));
		filePath.append(File.separator).append("WEB-INF").append(File.separator).append("static")
		.append(File.separator).append("uploads").append(File.separator).append("shortcut").append(File.separator);
		filePath.append(DateUtil.format(new Date(), "yyyyMMdd"));
		File file = new File(filePath.toString());
		if ( !file.exists() ) {
			file.mkdirs();
		}
		
		return file.getPath();
	}
	/**
	 * 获取图片的web访问路径
	 * @return String
	 * koumiba
	 * 2017年4月8日
	 */
	private String getSurlPath(){
		return "/static/uploads/shortcut/"+DateUtil.format(new Date(), "yyyyMMdd")+"/";
	}
}
